<template>
    <main class="chat-container">
        <div class="messages-box" ref="messagesBox">
            <ul id="messages" >
                <li v-for="(messageDownload, index) in messageDownloads" :key="index" class="message">
                    <PersonCard :personInfo="messageDownload" />
                </li>
            </ul>
        </div>
        <form  class="input-form" @submit.prevent="sendMessage">
            <input v-model="newMessage" class="message-input" placeholder="Type your message" />
            <button type="button" class="send-button" @keyup.enter="sendMessage" @click="sendMessage">Send</button>
        </form>
    </main>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue';
import { useLayoutStore } from '@/store/modules/layout';
import PersonCard from './widget/PersonCard.vue';
import { useSocketStore } from '@/store/modules/socket';

const layoutStore = useLayoutStore()
const socketStore = useSocketStore()

const messagesBox = ref<HTMLElement | null>(null)
const newMessage = ref<string>('')

// 如果这样写，就只是一个快照信息。而不是跟随着store中的变化，当然刷新页面后，信息会重拉一次。
// 【不改了不好玩~~~呜呜】
// 所以我理解，为什么需要 getters 了！
const messageUpload: messageUpload = {
    message: "",
    name: layoutStore.userInfo.name,
    avatar: layoutStore.userInfo.avatar, 
    role: layoutStore.userInfo.Role.name, // role_name
}

const messageDownloads = ref<messageDownload[]>([])


let socket = null

onMounted(() => {
    const ws_chat = import.meta.env.VITE_APP_WS_CHAT
    socket = new WebSocket(ws_chat)
    socket.onopen = (event) => {
        console.log('WebSocket connected:', event);
    }
    socket.onmessage = (event) => {
        messageDownloads.value.push(JSON.parse(event.data))
        scrollToBottom()
    }
    socket.onerror = (event) => {
        console.error('WebSocket error:', event)
    }
    socket.onclose = (event) => {
        console.log('WebSocket closed:', event)
    }

    socketStore.clickMsgSend()
})

onUnmounted(() => {
    if (socket) {
        socket.close()
        socket = null
    }
})

const sendMessage = () => {
    if (newMessage.value) {
        messageUpload.message = newMessage.value
        socket.send(JSON.stringify(messageUpload))
        newMessage.value = ''
    }
}

const scrollToBottom = () => {
    nextTick(() => {
        if (messagesBox.value) {
            messagesBox.value.scrollTop = messagesBox.value.scrollHeight
        }
    })
}
</script>

<style scoped>
.chat-container {
    display: flex;
    flex-direction: column;
    height: 80%;
    max-width: 80%;
    margin: auto;
    border: 1px solid #ccc;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(7, 2, 2, 0.1);
}

.messages-box {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    background-color: #111111;
    max-height: 700px;
}

#messages {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

.message {
    margin: 10px 0;
}

.message-content {
    display: inline-block;
    padding: 8px 12px;
    border-radius: 20px;
    max-width: 80%;
}

.input-form {
    display: flex;
    padding: 10px;
    background-color: #fff;
    border-top: 1px solid #ccc;
}

.message-input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 20px;
    margin-right: 10px;
}

.send-button {
    padding: 10px 20px;
    border: none;
    border-radius: 20px;
    background-color: #4caf50;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s;
}

.send-button:hover {
    background-color: #45a049;
}
</style>
